package com.oss.service.impl;


import org.oss.client.dto.BaseRequest;
import org.oss.client.dto.OssSecurityResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.oss.base.BaseConst;
import com.oss.base.util.HttpUtil;
import com.oss.base.util.PolicyBuilder;
import com.oss.service.IEhcacheService;
import com.oss.service.ISecurityService;
import com.oss.vo.UserAuth;

@Service("securityService")
public class SecurityServiceImpl implements ISecurityService{
	@Autowired
	private IEhcacheService ehcacheService;
	
	public OssSecurityResponse getStsFromOss(BaseRequest req, UserAuth auth) {
		String cacheKey = buidKey(req,auth);
		try {
			OssSecurityResponse res = (OssSecurityResponse) ehcacheService.getCacheElement(cacheKey);
			
			if(res != null){
				return res;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		try {
			String roleArn = auth.getAccConfig().getAccRole();
			String roleSessionName = auth.getLoginName();
			
			String policy = new PolicyBuilder()
			.setParam(BaseConst.POLICY_COND_ACTION, req.getMethod())
			.setParam(BaseConst.POLICY_COND_RESOURCE, req.getPath())
			.setParam(BaseConst.POLICY_COND_BUCKET, auth.getBucket())
			.build();
        
		
			IClientProfile profile = DefaultProfile.getProfile(
						auth.getAccConfig().getAccRegion(), auth.getAccConfig().getAccId(), auth.getAccConfig().getAccSecret());
			DefaultAcsClient client = new DefaultAcsClient(profile);
			
			// 创建一个 AssumeRoleRequest 并设置请求参数
			final AssumeRoleRequest request = new AssumeRoleRequest();


			request.setRoleArn(roleArn);
			request.setRoleSessionName(roleSessionName);
			request.setPolicy(policy);
			System.out.println(policy);
			// 发起请求，并得到response
			final AssumeRoleResponse response = client.getAcsResponse(request);

			OssSecurityResponse res = buildResponse(response,req,req.getPath());
			
			try {
				ehcacheService.addToCache(cacheKey, res);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return res;
		} catch (ClientException e) {
			return HttpUtil.buildFailedRes(OssSecurityResponse.class,e);
		}catch (Exception e) {
			e.printStackTrace();
			return HttpUtil.buildFailedRes(OssSecurityResponse.class,new ClientException(BaseConst.RESPONSE_CODE_NOAUTH, e.getMessage()));
		}
	}

	private String buidKey(BaseRequest req, UserAuth auth) {
		StringBuffer cacheKey = new StringBuffer();
		cacheKey.append(req.getBucket()+";");
		cacheKey.append(req.getEndpoint()+";");
		cacheKey.append(req.getMethod()+";");
		cacheKey.append(req.getPath()+";");
		cacheKey.append(auth.getAccConfig().getAccRole());
		cacheKey.append(auth.getAccConfig().getAccId()+";");
		cacheKey.append(auth.getAccConfig().getAccSecret()+";");
		return cacheKey.toString();
	}


	private OssSecurityResponse buildResponse(AssumeRoleResponse response, BaseRequest req,String key) {
		OssSecurityResponse res = new OssSecurityResponse();
		
		res.setAccessKeyId(response.getCredentials().getAccessKeyId());
		res.setAccessKeySecret(response.getCredentials().getAccessKeySecret());
		res.setSecurityToken(response.getCredentials().getSecurityToken());
		res.setBucketName(req.getBucket());
		res.setEndpoint(req.getEndpoint());
		res.setKey(key);
		res.setResultCode(BaseConst.RESPONSE_CODE_SUCCESS);
		res.setResultMsg(response.getRequestId());
		
		
		return res;
	}

	

	
	
	
	

}
